package csu.web.credit_bank.controller;

import csu.web.credit_bank.pojo.CreditCertification;
import csu.web.credit_bank.pojo.CreditRecord;
import csu.web.credit_bank.pojo.CreditSummary;
import csu.web.credit_bank.pojo.dto.CourseCertificationRequestDTO;
import csu.web.credit_bank.pojo.dto.PoetryQuestionDTO;
import csu.web.credit_bank.service.CreditCertificationsService;
import csu.web.credit_bank.service.CreditRecordsService;
import csu.web.credit_bank.service.CreditSummaryService;
import csu.web.credit_bank.service.PoetryChallengeService;
import csu.web.credit_bank.utils.JwtHelper;
import csu.web.credit_bank.utils.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/credits")

public class CreditsController {

    @Autowired
    private CreditCertificationsService certificationsService;
    @Autowired
    private CreditRecordsService recordsService;
    @Autowired
    private CreditSummaryService summaryService;
    @Autowired
    private JwtHelper jwtHelper; // 注入 JwtHelper 以便从 Token 中获取用户ID
    @Autowired
    private PoetryChallengeService poetryChallengeService;

    // --- 学分认证(CreditCertification)的CRUD ---
    @PostMapping("/certifications")
    public Result<CreditCertification> createCertification(@RequestBody CreditCertification certification) {
        try {
            return Result.success("认证申请提交成功", certificationsService.createCertification(certification));
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }

    @GetMapping("/certifications/{id}")
    public Result<CreditCertification> getCertificationById(@PathVariable String id) {
        CreditCertification cert = certificationsService.getCertificationById(id);
        return cert != null ? Result.success(cert) : Result.failure("认证申请未找到");
    }

    @GetMapping("/certifications")
    public Result<IPage<CreditCertification>> getCertificationList(@RequestParam(defaultValue = "1") int page, @RequestParam(defaultValue = "10") int size) {
        return Result.success(certificationsService.page(new Page<>(page, size)));
    }

    @PutMapping("/certifications/{id}")
    public Result<CreditCertification> updateCertification(@PathVariable String id, @RequestBody CreditCertification certification) {
        certification.setId(id);
        CreditCertification updatedCert = certificationsService.updateCertification(certification);
        return updatedCert != null ? Result.success("认证信息更新成功", updatedCert) : Result.failure("认证信息更新失败");
    }

    @DeleteMapping("/certifications/{id}")
    public Result<Void> deleteCertification(@PathVariable String id) {
        return certificationsService.deleteCertification(id) ? Result.success("认证申请删除成功") : Result.failure("认证申请删除失败");
    }

    // --- 学分记录(CreditRecord)的CRUD ---
    @PostMapping("/records")
    public Result<CreditRecord> createRecord(@RequestBody CreditRecord record) {
        try {
            CreditRecord creditRecord=recordsService.createCreditRecord(record);
            return Result.success("添加学分"+creditRecord.getCredits());
        } catch (Exception e) {
            return Result.failure(e.getMessage());
        }
    }

    @GetMapping("/records/{id}")
    public Result getRecordById(@PathVariable String id) {
        List<CreditRecord> records = recordsService.getCreditRecordById(id);
        return records != null ? Result.success(records) : Result.failure("学分记录未找到");
    }

    // --- 学分汇总(CreditSummary)的CRUD ---
    @GetMapping("/summary/{userId}")
    public Result<CreditSummary> getSummaryByUserId(@PathVariable String userId) {
        CreditSummary summary = summaryService.getCreditSummaryByUserId(userId);
        return summary != null ? Result.success(summary) : Result.failure("学分汇总未找到");
    }

    @PutMapping("/summary/{userId}")
    public Result<CreditSummary> updateSummary(@PathVariable String userId, @RequestBody CreditSummary summary) {
        summary.setUserId(userId);
        CreditSummary updatedSummary = summaryService.updateCreditSummary(summary);
        return updatedSummary != null ? Result.success("学分汇总更新成功", updatedSummary) : Result.failure("学分汇总更新失败");
    }

    @GetMapping("/new-poetry/question")
    public Result<PoetryQuestionDTO> getPoetryQuestion(@RequestHeader("Authorization") String authorizationHeader) {
        String token = jwtHelper.getTokenFromHeader(authorizationHeader);
        String userId = jwtHelper.getUserId(token);
        if (userId == null) {
            return Result.failure("用户未认证");
        }
        return poetryChallengeService.getPoetryChallenge(userId);
    }

    @PostMapping("/new-poetry/challenge")
    public Result<Void> handleNewPoetryChallenge(@RequestBody Map<String, Object> payload,
                                                 @RequestHeader("Authorization") String authorizationHeader) {
        String token = null;
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            token = authorizationHeader.substring(7);
        }

        if (token == null || token.isEmpty()) {
            return Result.failure("认证失败：Token缺失或格式不正确");
        }

        // 验证 Token 是否有效，并从 Token 中获取用户ID
        String userId = jwtHelper.getUserId(token);
        if (userId == null || "null".equals(userId)) {
            return Result.failure("无法获取用户信息，请重新登录");
        }

        String poemId = (String) payload.get("poemId");
        List<String> userAnswers = (List<String>) payload.get("userAnswers");

        // **核心修改：将 userId 作为参数传递给 PoetryChallengeService**
        return poetryChallengeService.processChallenge(userId, poemId, userAnswers);
    }
    /**
     * 新增：提交课程学分认证申请
     * POST /credits/course-certifications
     *
     * @param requestDTO 包含课程名称、图片URL和额外描述的请求体
     * @param authorizationHeader JWT token，从请求头中获取，用于提取当前登录用户ID
     * @return 认证申请结果
     */
    @PostMapping("/course-certifications")
    public Result<CreditCertification> createCourseCertification(@RequestBody CourseCertificationRequestDTO requestDTO,
                                                                 @RequestHeader("Authorization") String authorizationHeader) {
        String token = null;
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            token = authorizationHeader.substring(7);
        }

        if (token == null || token.isEmpty()) {
            return Result.failure("认证失败：Token缺失或格式不正确");
        }

        String userId = jwtHelper.getUserId(token);
        if (userId == null || "null".equals(userId)) {
            return Result.failure("无法获取用户信息，请重新登录");
        }

        requestDTO.setApplicantId(userId); // 设置申请人ID

        try {
            CreditCertification createdCertification = certificationsService.createCourseCertification(requestDTO);
            return Result.success("课程学分认证申请提交成功", createdCertification);
        } catch (IllegalArgumentException e) {
            // 捕获服务层抛出的业务异常，例如未找到课程
            return Result.failure(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failure("课程学分认证申请失败: " + e.getMessage());
        }
    }
    @GetMapping("/check-course-credit")
    public Result<Boolean> checkStudentCourseCreditStatus(@RequestParam("courseName") String courseName,
                                                          @RequestHeader("Authorization") String authorizationHeader) {
        String token = null;
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            token = authorizationHeader.substring(7);
        }

        if (token == null || token.isEmpty()) {
            return Result.failure("认证失败：Token缺失或格式不正确");
        }

        String userId = jwtHelper.getUserId(token);
        if (userId == null || "null".equals(userId)) {
            return Result.failure("无法获取用户信息，请重新登录");
        }

        boolean hasCertified = recordsService.hasStudentReceivedCourseCredit(userId, courseName); // 调用新添加的服务方法
        return Result.success(hasCertified);
    }

}
